package com.deodar.kettle.platform.common.util;


import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class JSONArray extends ArrayList<Object> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public JSONArray() {
		
	}
	
	public JSONArray(int initialCapacity) {
		super(initialCapacity);
	}

	public JSONArray(List<Object> list) {
		if(list != null)
			this.addAll(list);
	}

	public static JSONArray fromObject(String json) throws JsonParseException, JsonMappingException, IOException {
		JSONArray jsonArray = new JSONArray();
		if(!StringUtils.hasText(json))
			return jsonArray;

		ObjectMapper mapper = new ObjectMapper();
		return mapper.readValue(json, JSONArray.class);
	}
	
	public static JSONArray fromObject(List list) throws JsonParseException, JsonMappingException, IOException {
		return new JSONArray(list);
	}

	public String getString(int i) {
		return (String) get(i);
	}
	
	public JSONObject getJSONObject(int i) {
		Map<String, Object> m = (Map<String, Object>) get(i);
		return new JSONObject(m);
	}
	
	public String toString() {
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.writeValueAsString(this);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
